package com.shine.icis.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import com.shine.icis.exception.ICISException;

import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpLoginException;

public class FTPHelper {
	private String server = null;//FTP服务器的IP地址
	private String user = null;//登录FTP服务器的用户名
	private String password = null;//登录FTP服务器的用户名的口令
	private String path = null;//FTP服务器上的路径
	
	public void init(String ftpUrl) throws ICISException {
		ftpUrl = ftpUrl.replaceAll("\\\\", "/");
		if (ftpUrl.endsWith("/")) {
			ftpUrl = ftpUrl.substring(0, ftpUrl.length() - 1);
		}
		if (!isFtpPath(ftpUrl)) {
			throw new ICISException("FTP地址不正确");
		}
		ftpUrl = ftpUrl.substring(6, ftpUrl.length());
		int i = ftpUrl.indexOf("/");
		if (i != -1) {
			path = ftpUrl.substring(i);
			ftpUrl = ftpUrl.substring(0, i);
		}
		String[] tem = ftpUrl.split("@");
		if (tem.length != 2) {
			throw new ICISException("FTP地址不正确");
		}
		server = tem[1];
		ftpUrl = tem[0];
		tem = ftpUrl.split(":");
		if (tem.length != 2) {
			throw new ICISException("FTP地址不正确");
		}
		user = tem[0];
		password = tem[1];
	}
	
	/**
	 * 是否为FTP地址
	 * @param path
	 * @return
	 */
	public static boolean isFtpPath(String path) {
		return path.toLowerCase().startsWith("ftp://");
	}
	
	/**
	 * 测试FTP连接
	 * @param ftpUrl
	 * @return
	 * @throws ICISException
	 */
	public static boolean testFTP(String ftpUrl) throws ICISException {
		FTPHelper ftp = new FTPHelper();
		ftp.init(ftpUrl);
		
		FtpClient ftpClient;
		try {
			ftpClient = new FtpClient();
			ftpClient.openServer(ftp.server);
			ftpClient.login(ftp.user, ftp.password);
			//服务器上创建上传目录
			if (ftp.path != null) {
//				ftpClient.sendServer("MKD " + path + "\r\n");
//				ftpClient.readServerResponse();
				ftpClient.cd(ftp.path);
			}
			ftpClient.closeServer();
		} catch(FileNotFoundException e) {
			e.printStackTrace();
			throw new ICISException("FTP目录不存在");
		} catch(FtpLoginException e) {
			e.printStackTrace();
			throw new ICISException("FTP登录出错");
		} catch(Exception e) {
			e.printStackTrace();
			throw new ICISException("FTP连接出错");
		}
		return true;
	}
	
	/**
	 * 把本地目录下的加密后的文件上传到FTP ，并在原有目录下，将这些已上传的文件删除掉
	 * @param ftpUrl
	 * @param dirName
	 * @param soursePath
	 * @throws ICISException
	 * @throws IOException
	 */
	public static void uploadToFTP(String ftpUrl, String dirName, String soursePath) throws ICISException, IOException{
		FTPHelper ftp = new FTPHelper();
		ftp.init(ftpUrl);
		
		File localDir = new File(soursePath);//本地要上传的目录
		File[] uploadFiles = localDir.listFiles();
		if (uploadFiles.length == 0) {
			return;
		}
			
		FtpClient ftpClient = null;
		TelnetOutputStream os = null;
		FileInputStream is = null;
		try {
			ftpClient = new FtpClient();
			ftpClient.openServer(ftp.server);
			ftpClient.login(ftp.user, ftp.password);
			
			String uploadPath = ftp.path + "/" + dirName;//FTP上传目录
			//服务器上创建上传目录
			ftpClient.sendServer("MKD " + uploadPath + "\r\n");
			ftpClient.readServerResponse();
			//进入上传目录
			ftpClient.cd(uploadPath);
			// 用2进制上传
			ftpClient.binary();

			for (File file : uploadFiles) {
				os = ftpClient.put(file.getName());
				is = new FileInputStream(file);
				byte[] bytes = new byte[1024 * 100];
				int c;
				while ((c = is.read(bytes)) != -1) {
					os.write(bytes, 0, c);
				}
				os.close();
				is.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient != null) {
				ftpClient.closeServer();
			}
		}

	}
	
	/**
	 * 删除FTP上的目录
	 * @param ftpUrl
	 * @param dirName
	 * @throws ICISException
	 * @throws IOException
	 */
	public static void delFiles(String ftpUrl, String dirName) throws ICISException, IOException{
		FTPHelper ftp = new FTPHelper();
		ftp.init(ftpUrl);
			
		FtpClient ftpClient = null;
		try {
			ftpClient = new FtpClient();
			ftpClient.openServer(ftp.server);
			ftpClient.login(ftp.user, ftp.password);
			
			String uploadPath = ftp.path + "/" + dirName;//FTP上传目录
			//进入上传目录
			try {
				ftpClient.cd(uploadPath);
			} catch(FileNotFoundException e) {
				return;
			}
			
			BufferedReader dr = new BufferedReader(new InputStreamReader(ftpClient.list()));
			String s = null;
			while ( (s = dr.readLine()) != null) {
				String name = parseFileName(s);
				if (name!= null && !name.equals(".") && !name.equals("..")) {
					ftpClient.sendServer("DELE " + name + "\r\n");
					ftpClient.readServerResponse();
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient != null) {
				ftpClient.closeServer();
			}
		}

	}
	
	/**
	 * 解析文件名
	 * @param line
	 * @return
	 */
	private static String parseFileName(String line) {
		if (line == null) {
			return null;
		}
		List<String> s1 = new ArrayList<String>();
		StringTokenizer st = new StringTokenizer(line, " ");
		while (st.hasMoreTokens()) {
			s1.add(st.nextToken());
		}
		if (s1.size() < 8) {
			return null;
		}
		return s1.get(8);
	}
	
	/**
	 * FTP上创建文件
	 * @param ftpUrl
	 * @param dirName
	 * @param filename
	 * @throws ICISException
	 * @throws IOException
	 */
	public static void createNewFile(String ftpUrl, String dirName, String filename) throws ICISException, IOException{
		FTPHelper ftp = new FTPHelper();
		ftp.init(ftpUrl);
			
		FtpClient ftpClient = null;
		try {
			ftpClient = new FtpClient();
			ftpClient.openServer(ftp.server);
			ftpClient.login(ftp.user, ftp.password);
			
			String uploadPath = ftp.path + "/" + dirName;//FTP上传目录
			//进入上传目录
			ftpClient.cd(uploadPath);
			//服务器上创建文件
			TelnetOutputStream os = ftpClient.put(filename);
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient != null) {
				ftpClient.closeServer();
			}
		}

	}
}
